{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "文件夹 '1227' 已存在。\n",
      "文件夹 '大法寺镇' 已存在。\n",
      "\n",
      "导出属性表：E:\\MyDocument\\ArcGis\\DT\\基地面修改\\1227\\大法寺镇\\凤咀社区\\凤咀社区_白膜02\n",
      "文件夹 '白膜' 已创建。\n",
      "文件夹 'fengju02' 已创建。\n",
      "已删除列: FID, sqjcwhmc\n",
      "文件已成功处理并保存。\n",
      "\n",
      "excel文件名： 大法寺镇凤咀社区122719.xlsx\n",
      "\n",
      "导出属性表：E:\\MyDocument\\ArcGis\\DT\\基地面修改\\1227\\大法寺镇\\刘凤袍村\\刘凤袍村_白膜02\n",
      "文件夹 '白膜' 已创建。\n",
      "文件夹 'liufengpao02' 已创建。\n",
      "已删除列: FID, sqjcwhmc\n",
      "文件已成功处理并保存。\n",
      "\n",
      "excel文件名： 大法寺镇刘凤袍村122719.xlsx\n",
      "\n",
      "导出属性表：E:\\MyDocument\\ArcGis\\DT\\基地面修改\\1227\\大法寺镇\\月塘村\\月塘村_白膜02\n",
      "文件夹 '白膜' 已创建。\n",
      "文件夹 'yuetang02' 已创建。\n",
      "已删除列: FID, sqjcwhmc\n",
      "文件已成功处理并保存。\n",
      "\n",
      "excel文件名： 大法寺镇月塘村122719.xlsx\n",
      "\n",
      "导出属性表：E:\\MyDocument\\ArcGis\\DT\\基地面修改\\1227\\大法寺镇\\李边村\\李边村_白膜02\n",
      "文件夹 '白膜' 已创建。\n",
      "文件夹 'libian02' 已创建。\n",
      "已删除列: FID, sqjcwhmc\n",
      "文件已成功处理并保存。\n",
      "\n",
      "excel文件名： 大法寺镇李边村122719.xlsx\n",
      "\n",
      "导出属性表：E:\\MyDocument\\ArcGis\\DT\\基地面修改\\1227\\大法寺镇\\芭茅巷村\\芭茅巷村_白膜02\n",
      "文件夹 '白膜' 已创建。\n",
      "文件夹 'bamaoxiang02' 已创建。\n",
      "已删除列: FID, sqjcwhmc\n",
      "文件已成功处理并保存。\n",
      "\n",
      "excel文件名： 大法寺镇芭茅巷村122719.xlsx\n",
      "\n",
      "导出属性表：E:\\MyDocument\\ArcGis\\DT\\基地面修改\\1227\\大法寺镇\\茶山村\\茶山村_白膜02\n",
      "文件夹 '白膜' 已创建。\n",
      "文件夹 'chashan02' 已创建。\n",
      "已删除列: FID, sqjcwhmc\n",
      "文件已成功处理并保存。\n",
      "\n",
      "excel文件名： 大法寺镇茶山村122719.xlsx\n",
      "\n",
      "导出属性表：E:\\MyDocument\\ArcGis\\DT\\基地面修改\\1227\\大法寺镇\\西畈村\\西畈村_白膜02\n",
      "文件夹 '白膜' 已创建。\n",
      "文件夹 'xifan02' 已创建。\n",
      "已删除列: FID, sqjcwhmc\n",
      "文件已成功处理并保存。\n",
      "\n",
      "excel文件名： 大法寺镇西畈村122719.xlsx\n",
      "\n",
      "导出了 7 个要素。\n",
      "\n"
     ]
    }
   ],
   "source": [
    "import arcpy\n",
    "from datetime import datetime\n",
    "from pypinyin import lazy_pinyin\n",
    "import pandas as pd\n",
    "import os\n",
    "import shutil\n",
    "\n",
    "def check_and_create_folder(folder_path, folder_name):\n",
    "    full_path = os.path.join(folder_path, folder_name)\n",
    "\n",
    "    if not os.path.exists(full_path):\n",
    "        os.makedirs(full_path)\n",
    "        print(f\"文件夹 '{folder_name}' 已创建。\")\n",
    "    else:\n",
    "        print(f\"文件夹 '{folder_name}' 已存在。\")\n",
    "\n",
    "    return full_path\n",
    "\n",
    "def create_town(base_path, townName):\n",
    "    # 检查并创建镇文件夹\n",
    "    town_folder = check_and_create_folder(base_path, townName)\n",
    "\n",
    "    return town_folder\n",
    "\n",
    "def create_wh(base_path, whiteModelName, wmName):\n",
    "    # 检查并创建白膜文件夹\n",
    "    whiteModel_folder = check_and_create_folder(base_path, whiteModelName)\n",
    "    # 检查并创建白膜名称文件夹\n",
    "    wm_folder = check_and_create_folder(whiteModel_folder, wmName)\n",
    "\n",
    "    return whiteModel_folder, wm_folder\n",
    "\n",
    "def extract_village_name(village_value):\n",
    "    \"\"\"\n",
    "    根据 village_value 提取 \"村\" 或 \"社区\" 前的字符串。\n",
    "    :param village_value: 包含 \"村\" 或 \"社区\" 的字符串\n",
    "    :return: 提取后的字符串\n",
    "    \"\"\"\n",
    "    if \"村\" in village_value:\n",
    "        return village_value.split(\"村\")[0].strip()\n",
    "    elif \"社区\" in village_value:\n",
    "        return village_value.split(\"社区\")[0].strip()\n",
    "    else:\n",
    "        return village_value  # 如果没有找到 \"村\" 或 \"社区\"，则返回原始值\n",
    "\n",
    "def generate_wmName(village_padding, version=\"\", isagain=False):\n",
    "    \"\"\"\n",
    "    生成 wmName。\n",
    "    :param village_padding: 处理后的 village_value\n",
    "    :param version: 版本号，默认为空字符串\n",
    "    :param isagain: 是否添加版本号，默认为 False\n",
    "    :return: 生成的 wmName\n",
    "    \"\"\"\n",
    "    simple_pinyin_list = lazy_pinyin(village_padding)\n",
    "    wmName = ''.join(simple_pinyin_list) + (version if isagain else '')\n",
    "    return wmName\n",
    "\n",
    "def process_excel(file_path, columns_to_drop=None):\n",
    "    \"\"\"\n",
    "    处理 Excel 文件，删除指定列并保存修改。\n",
    "\n",
    "    参数:\n",
    "    - file_path (str): Excel 文件的路径。\n",
    "    - columns_to_drop (list or None): 要删除的列名列表，默认为 ['FID', 'sqjcwhmc']。\n",
    "\n",
    "    返回:\n",
    "    - bool: 如果处理成功返回 True，否则返回 False。\n",
    "    \"\"\"\n",
    "    try:\n",
    "        # 设置默认要删除的列\n",
    "        if columns_to_drop is None:\n",
    "            columns_to_drop = ['FID', 'sqjcwhmc']\n",
    "\n",
    "        # 读取 Excel 文件\n",
    "        df = pd.read_excel(file_path)\n",
    "\n",
    "        # 检查并删除指定的列\n",
    "        existing_columns = [col for col in columns_to_drop if col in df.columns]\n",
    "        if existing_columns:\n",
    "            df.drop(columns=existing_columns, inplace=True)\n",
    "            print(f\"已删除列: {', '.join(existing_columns)}\")\n",
    "        else:\n",
    "            print(\"文件中没有需要删除的列。\")\n",
    "\n",
    "        # 保存修改后的文件\n",
    "        df.to_excel(file_path, index=False)\n",
    "        print(\"文件已成功处理并保存。\")\n",
    "        return True\n",
    "    except Exception as e:\n",
    "        print(f\"处理文件时发生错误: {e}\")\n",
    "        return False\n",
    "\n",
    "# 获取当前工程\n",
    "aprx = arcpy.mp.ArcGISProject(\"CURRENT\")\n",
    "\n",
    "# 获取活动的地图或场景\n",
    "active_map_or_scene = aprx.activeMap\n",
    "                                \n",
    "\n",
    "# 获取所有唯一的 sqjcwhmc 值\n",
    "version = \"02\"\n",
    "isagain = True\n",
    "whiteModelName = \"白膜\"\n",
    "sqjcwhmc_field_name = \"sqjcwhmc\"\n",
    "                  \n",
    "townName = \"大法寺镇\"\n",
    "village_list = [\"凤咀社区\", \"刘凤袍村\", \"月塘村\", \"李边村\", \"芭茅巷村\", \"茶山村\", \"西畈村\"]                  \n",
    "# 查找对应名称的图层\n",
    "target_layer_name = \"大法寺镇_中心镇区02\"\n",
    "out_execel_path = r\"E:\\MyDocument\\ArcGis\\DT\\output\"\n",
    "                  \n",
    "# 创建输出目录\n",
    "path_to_check = r\"E:\\MyDocument\\ArcGis\\DT\\基地面修改\"\n",
    "folder_to_find = datetime.now().strftime(\"%m%d\")            \n",
    "base_path = check_and_create_folder(path_to_check, folder_to_find)\n",
    "output_directory = create_town(base_path, townName)  \n",
    "\n",
    "target_layer = None\n",
    "for lyr in active_map_or_scene.listLayers():\n",
    "    if lyr.name == target_layer_name:\n",
    "        target_layer = lyr\n",
    "        break\n",
    "\n",
    "if target_layer is None:\n",
    "    print(\"图层未找到。\")\n",
    "    exit\n",
    "\n",
    "# 获取 sqjcwhmc 字段\n",
    "sqjcwhmc_field = [field for field in arcpy.ListFields(target_layer) if field.name == \"sqjcwhmc\"][0]\n",
    "\n",
    "\n",
    "\n",
    "# 遍历每个唯一的 sqjcwhmc 值\n",
    "count = 0\n",
    "for village_value in village_list:\n",
    "    # 创建文件夹\n",
    "    vilage_path = os.path.join(output_directory, village_value)\n",
    "    if not os.path.exists(vilage_path):\n",
    "        os.makedirs(vilage_path)\n",
    "    \n",
    "    # 导出属性表\n",
    "    output_table_path = os.path.join(vilage_path, f\"{village_value}_白膜\" + (version if isagain else ''))\n",
    "    where_clause = f\"{sqjcwhmc_field_name} = '{village_value}'\"\n",
    "    out_layer_or_view, countStr = arcpy.management.SelectLayerByAttribute(\n",
    "        target_layer,\n",
    "        \"NEW_SELECTION\",\n",
    "        where_clause\n",
    "    )\n",
    "    arcpy.conversion.ExportFeatures(\n",
    "        out_layer_or_view, \n",
    "        output_table_path\n",
    "    )\n",
    "    print(f\"\\r\\n导出属性表：{output_table_path}\")\n",
    "    count += 1\n",
    "                  \n",
    "    # 删除字段\n",
    "\n",
    "    # 创建白膜文件夹\n",
    "    # 当village_value包含\"村\"时，获取”村“前的字符串; 当village_value包含\"社区\"时，获取”社区“前的字符串\n",
    "    village_padding = extract_village_name(village_value);\n",
    "    wmName = generate_wmName(village_padding, version, isagain)\n",
    "    whiteModel_folder, wm_folder = create_wh(vilage_path, whiteModelName, wmName)\n",
    "    \n",
    "    # 导出excel\n",
    "    excel_name = townName + village_value + datetime.now().strftime(\"%m%d%H\") + \".xlsx\"\n",
    "    excel_path = os.path.join(vilage_path, excel_name)\n",
    "    arcpy.conversion.TableToExcel(f\"{village_value}_白膜\" + (version if isagain else ''), excel_path)\n",
    "    process_excel(excel_path, columns_to_drop=['FID', 'sqjcwhmc'])\n",
    "                  \n",
    "    # 获取源文件的文件名\n",
    "    file_name = os.path.basename(excel_path)\n",
    "\n",
    "    # 构建目标文件的完整路径\n",
    "    destination_file_path = os.path.join(out_execel_path, file_name)             \n",
    "    shutil.copy2(excel_path, destination_file_path)\n",
    "    print(\"\\r\\nexcel文件名：\", excel_name)  \n",
    "    \n",
    "\n",
    "print(f\"\\r\\n导出了 {count} 个要素。\\r\\n\")\n",
    "    \n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "ArcGISPro",
   "language": "Python",
   "name": "python3"
  },
  "language_info": {
   "file_extension": ".py",
   "name": "python",
   "version": "3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
